import json
from django.shortcuts import render,HttpResponse

# Create your views here.

loginArr = []

def getBackXml(xmlObj):
  # 交换发送者和接收者
  obj = xmlObj['xml']
  tempStr = obj['ToUserName']
  obj['ToUserName'] = obj['FromUserName']
  obj['FromUserName'] = tempStr
  obj['CreateTime'] = str(int(obj['CreateTime']) +100)

  # // 回复信息给 微信服务器
  content = ''
  if obj['MsgType'] == 'text':
    if obj['Content'] == '1':
      content = '很快就成功了'
    elif obj['Content'] == '2':
      content = '再坚持一会，就成功了'
    elif obj['Content'].find('爱') !=-1:
      content = '爱你一万年！'
    else:
      content = '你可以发送: 1，2，3，爱你！'
    
  elif obj['MsgType'] == 'event':
    content = 'event事件'
    if obj['Event'] == 'SCAN':
      content = '好家伙，手机扫码'
    elif obj['Event'] == 'subscribe':
      content = '好家伙，欢迎您的关注！'
    elif obj['Event'] == 'unsubscribe':
      content = '好家伙，你居然敢取笑关注？'
  else:
    content = '其他信息来源！'
  
  msgStr = '''<xml>
      <ToUserName><![CDATA['''+ obj['ToUserName'] +''']]></ToUserName>
      <FromUserName><![CDATA['''+ obj['FromUserName'] +''']]></FromUserName>
      <CreateTime>'''+ obj['CreateTime'] +'''</CreateTime>
      <MsgType><![CDATA[text]]></MsgType>
      <Content><![CDATA['''+ content +''']]></Content>
    </xml>'''
  return msgStr

def index(request):
  if request.method == 'POST':
    print("这是post请求",request.body)
    from xml.dom import minidom
    import json as simplejson

    print("request.body-类型：", type(request.body))

    #pseudo code that returns actual xml data as a string from remote server.
    # result = urlfetch.fetch(url,'','get');
    # resStr = str(request.body, encoding = "utf-8")
    # print("resStr: ",resStr)

    # dom = minidom.parseString(request.body)
    # print("dom", type(dom))
    # json = simplejson.load(dom)

    import xmltodict, json

    obj = xmltodict.parse(request.body)
    print("obj",obj)
    EventKey = ''
    if 'EventKey' in obj['xml']:
      EventKey = obj['xml']['EventKey']
    print("EventKey: ", type(EventKey), EventKey)
    if EventKey.find('_') !=-1:
      EventKey = EventKey.split('_')[1]
    
    loginArr.append(EventKey)
    # 回复微信服务器
    backStr = getBackXml(obj)

  # 这是get请求
  else:
    backStr = "hello web python"
    print("这是get请求", request.method)

  return HttpResponse(backStr)

# 退出登录
def Logout(request):
  print(request.GET)
  myid = request.GET.get('myid')
  print("--------有人退出登录----logout-myid",myid, loginArr)
  isLogout = 1
  if(myid in loginArr):
    print("含有---删除该用户记录--")
    loginArr.remove(myid)
  print("loginArr", loginArr)
  return HttpResponse(isLogout)

def Login(request):
  print(request.GET)
  myid = request.GET.get('myid')
  print("--有人来问，是否登录--myid",myid, loginArr)
  isLogin = 0
  if(myid in loginArr):
    print("含有---")
    isLogin = 1
  return HttpResponse(isLogin)

wxConfig = {
  'appId': 'wx3680aee5b396cc0f',                    # 这个要改成你自己的
  'appsecret': '626c988a2e4af8cc459424187951792e',  # 这个也要改成你自己的
  'token': '123456', # 这个是你自己随便写的，写成123abc也行
}
def getQrCode(request):
  # python.analysis.extraPaths
  # json.dumps(): 对数据进行编码。将字典转成json
  # json.loads(): 对数据进行解码。将json转成字典

  import requests
  
  print(request.POST)
  print(request.body)
  jsonData = json.loads(request.body)
  print("json",jsonData, jsonData.keys())
  

  # 请求token
  token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+ wxConfig['appId'] +'&secret='+ wxConfig['appsecret']
  res = requests.get(token_url)
  tokenObj = res.json()
  print("token_url: ", tokenObj)
  print("token", tokenObj['access_token'])

  # 请求ticket
  ticket_url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='+tokenObj['access_token']
  tRes = requests.post(ticket_url, data=request.body)
  ticketObj = tRes.json()
  print("ticketObj: ", ticketObj)
  return HttpResponse(json.dumps(ticketObj))
